/* ******************************************************************
 * This file is part of the escal project and distributed under the
 * terms of the GNU General Public License Version 3
 * Copyright (C) 2008 Epocher (xijiaosdq@gmail.com)
 * See COPYING file for licensing information.
 *******************************************************************/

#include "escal.h"
#include "client_watcher.h"
#include <QTcpSocket>
using namespace Escal;

ClientWatcher::ClientWatcher(QTcpSocket *socket, QObject *parent)
	:QThread(parent)
{
	socket->setParent(NULL);
	socket->moveToThread(this);
	this->socket = socket;
}

ClientWatcher::~ClientWatcher(){
	qDebug() << "ClientWatcher::~ClientWatcher()";
	QThread::quit();
	wait();
	socket->deleteLater();
}

void ClientWatcher::run(){
	qDebug() << "ClientWatcher::run()";
	while(socket->waitForReadyRead()){
		QByteArray data;
		QTextStream stream(&data);
		QString string;
		int type;
		while(socket->canReadLine()){
			data=socket->readLine();
			qDebug() << "get message:" << data;
			stream >> type >> string;
			if(type==CMT_NEW_URL){
				qDebug() << "got url";
				emit getUrl(string);
			}
			else{
				qDebug() << "Unkown message type!";
			}
		}
		QByteArray array;
		QTextStream stream2(&array);
		stream2 << SMT_OK << " " << "OK" << endl;
		socket->write(array.constData(), array.size());
	}
	qDebug() << socket->errorString();
	emit quited(this);
	qDebug() << "ClientWatcher::run() out";
}	
